// 导入上传图片的包  定义上传图片的信息（图片名称，目录）
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置常量
const UPLOAD_CONFIG = {
    MAX_SIZE: 5 * 1024 * 1024, // 最大文件大小 5MB
    ALLOWED_TYPES: ['image/jpeg', 'image/png', 'image/gif' , 'image/jpg' ,'image/webp'], // 允许的文件类型
    UPLOAD_DIR: path.join(__dirname, '../public/imgs')//文件路径
};

// 确保上传目录存在
if (!fs.existsSync(UPLOAD_CONFIG.UPLOAD_DIR)) {
    fs.mkdirSync(UPLOAD_CONFIG.UPLOAD_DIR, { recursive: true });
}

// 文件过滤器
const fileFilter = (req, file, cb) => {
    if (UPLOAD_CONFIG.ALLOWED_TYPES.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(new Error('不支持的文件类型'), false);
    }
};

// 通过 filename 属性定制
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, UPLOAD_CONFIG.UPLOAD_DIR);
    },
    filename: (req, file, cb) => {
        const date = new Date();
        const dateString = date.toISOString().slice(0,10).replace(/-/g, '');
        const fileExt = path.extname(file.originalname) || '.' + file.mimetype.split('/')[1];
        const fileName = `${file.fieldname}-${dateString}-${Date.now()}${fileExt}`;
        cb(null, fileName);
    }
});

//生成的图片放入uploads文件夹下
const upload = multer({
    storage,
    fileFilter,
    limits: {
        fileSize: UPLOAD_CONFIG.MAX_SIZE
    }
});

// 导出处理图片的方法
module.exports = upload
